<template>
  <div>
    <div class="content-title">
      <span>服务(前置URL)</span>
    </div>
    <EditURL :data="environmentURL" />
    <div class="content-title">
      <span>环境变量</span>
    </div>
    <EditTable @change-edit-method="changeEditMethod" :data="environmentTable" @all-table-data="handleAllTableData" />
    <multipleEdit ref="multipleEditRef" :editorValue="editorValue" @update-editor-value="updateEditorValue"
      @text-to-json="handleTextToJSON" />
  </div>
</template>

<script setup lang="ts">
const message = useMessage() // 消息弹窗
import EditTable from '@/views/apiManage/debug/environment/components/EditTable.vue';
import EditURL from './EditURL.vue';
import multipleEdit from '@/views/apiManage/debug/dialog/MultipleEdit.vue'
import { evnjsonToTableData, evntableDataToJson } from '@/utils/index'
import { useCache } from '@/hooks/web/useCache'
const environmentTable = ref()
const environmentURL = ref()
const multipleEditRef = ref()
const editorValue = ref()
const { wsCache } = useCache()
const environmentParams = computed(() => wsCache.get('enviromentParams'))
/**
 * 响应批量编辑
 * */
const changeEditMethod = (tableData) => {
  multipleEditRef.value.open(tableData)
}
/**
 * 表格全部数据
 * */
const handleAllTableData = (data) => {
  editorValue.value = JSON.stringify(evntableDataToJson(data))
  environmentTable.value = data
}

/**
 * 批量数据编辑后回显到表格
 * */
const updateEditorValue = (data) => {
  environmentTable.value = evnjsonToTableData(JSON.parse(data))
  // handleAllTableData(environmentTable.value)
}
/**
 * 弹窗中text改变，触发editor改变
 * */
const handleTextToJSON = (data) => {
  editorValue.value = JSON.stringify(data)
}

/** 提交-保存环境变量 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submit = async () => {
  await nextTick()
  if (environmentTable.value.length !== 0) {
    if (environmentTable.value[environmentTable.value.length - 1].varName === '') {
      environmentTable.value.splice(environmentTable.value.length - 1, 1);
    }
  }
  let data = {
    ...environmentParams.value,
    envVarList: JSON.stringify(environmentTable.value)
  }
  wsCache.set('enviromentParams', data)
  message.success('保存成功')
  emit('success')
}


/**获取环境变量列表 */
const getList = async () => {
  const varList = environmentParams.value.envVarList
  environmentTable.value = typeof varList == 'string' ? JSON.parse(varList) : varList
  environmentURL.value = [{ serviceName: '默认服务', conditionUrl: environmentParams.value.conditionUrl }]
  handleAllTableData(environmentTable.value)
}
defineExpose({ submit })

onMounted(() => {
  getList()
})

</script>

<style scoped>
.content-title {
  margin: 15px 12px 8px;
  font-size: 14px;
  /* color: #344054; */
}
</style>
